package thread;

/**
 * 死锁
 * 死锁指的是两个(或多个)线程各自持有一个锁的同时等待对方释放其持有的锁
 * 的一个现象,此时会出现一种僵持状态,导致程序永远无法继续后续的执行.
 *
 *
 */
public class DeadLockDemo {
    private static Object spoon = new Object();//勺
    private static Object chopsticks = new Object();//筷子
    public static void main(String[] args) {
        Thread np = new Thread("北方人"){
            public void run(){
                String name = getName();//获取线程名字
                try{
                    System.out.println(name+":开始吃饭");
                    System.out.println(name+":去拿筷子...");
                    synchronized (chopsticks){
                        System.out.println(name+":拿起筷子吃饭...");
                        Thread.sleep(5000);

                        System.out.println(name+":吃完了饭,去拿勺子");
                        synchronized (spoon){
                            System.out.println(name+":拿起勺子喝汤...");
                            Thread.sleep(5000);
                        }
                        System.out.println(name+":喝完了汤并发下了勺");
                    }
                    System.out.println(name+":放下了筷子,吃饭完毕!");
                }catch(Exception e){
                }
            }
        };
        Thread sp = new Thread("南方人"){
            public void run(){
                String name = getName();//获取线程名字
                try{
                    System.out.println(name+":开始吃饭");
                    System.out.println(name+":去拿勺子...");
                    synchronized (spoon){
                        System.out.println(name+":拿起勺子喝汤...");
                        Thread.sleep(5000);

                        System.out.println(name+":喝完了汤,去拿筷子");
                        synchronized (chopsticks){
                            System.out.println(name+":拿起筷子吃饭...");
                            Thread.sleep(5000);
                        }
                        System.out.println(name+":吃完了饭并发下了筷子");
                    }
                    System.out.println(name+":放下了勺子,吃饭完毕!");
                }catch(Exception e){
                }
            }
        };

        np.start();
        sp.start();




    }
}








